package trucaso;
/*
 *  The deck class contains all the cards in an array
 */
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

import javax.imageio.ImageIO;
import javax.swing.JOptionPane;

public class Deck {
	Card[] cards; //Array with the cards
	
	protected Deck() {
		cards = new Card[40];
		loadCards();
		try {
			java.net.URL url = Deck.class.getResource("cards/back.gif");
			BufferedImage i = ImageIO.read(url);
			Card.setCardBack(i);
		}catch(Exception ex) {
			JOptionPane.showMessageDialog(null,"Error al cargar la parte de atrás de las cartas...","Error!",JOptionPane.ERROR_MESSAGE);
		}
		
	}
	
	//Loads the cards from the respective image files and
	//assigns each one a value, then inserts each card in the array
	protected void loadCards() {
		String[] fn = {"1e","2e","3e","4e","5e","6e","7e","10e","11e","12e",
				"1p","2p","3p","4p","5p","6p","7p","10p","11p","12p",
				"1o","2o","3o","4o","5o","6o","7o","10o","11o","12o",
				"1c","2c","3c","4c","5c","6c","7c","10c","11c","12c"};
		
		int[] vals = {14,9,10,1,2,3,12,5,6,7,
					13,9,10,1,2,3,4,5,6,7,
					8,9,10,1,2,3,11,5,6,7,
					8,9,10,1,2,3,4,5,6,7};
		
		int[] env = {1,2,3,4,5,6,7,0,0,0,1,2,3,4,5,6,7,0,0,0,
					 1,2,3,4,5,6,7,0,0,0,1,2,3,4,5,6,7,0,0,0};
		
		char[] type = {'e','e','e','e','e','e','e','e','e','e','e','e',
						'p','p','p','p','p','p','p','p','p','p','p','p',
						'o','o','o','o','o','o','o','o','o','o','o','o',
						'c','c','c','c','c','c','c','c','c','c','c','c'};
		
		for(int i=0;i<40;i++) {
			loadCard(i,vals[i],env[i],type[i],fn[i]);
		}
	}
	
	//Resets the deck
	protected void shuffle() {
		int l = cards.length;
		for(int i = 0;i<l;i++) {
			cards[i].setVisible(false);
			cards[i].setInGame(false);
		}
	}
	
	//Loads a Card from a file.
	protected void loadCard(int pos,int val,int env,char t,String f) {
		Card c;
		
		java.net.URL url = Deck.class.getResource("cards/"+f+".gif");
		
		try {
		c = new Card(pos,val,env,t,ImageIO.read(url));
		} catch(IOException x) { 
			c = null;
			JOptionPane.showMessageDialog(null,"Error al cargar"+url+". Alguien habrá modificado el jar","Error!",JOptionPane.ERROR_MESSAGE);
		}
		
		cards[pos] = c;
	}
	
	//Returns a random card and sets it in game to prevent it from 
	//appearing more than once
	protected Card getRandomCard() {
		Random r;
		r = new Random();
		Card c = cards[r.nextInt(40)];
		while(c.isInGame()) {
			c = cards[r.nextInt(40)];
		}
		c.setInGame(true);
		
		return c;
	}
	
	protected Card getCard(int number) {
		return cards[number];
	}

}
